/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*   File:      SwitchButton.cpp
*   Author:    刘洋兵
*   Function:  设置滑动模块控件
*   Time:      2025-10-10
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

#include "SwitchButton.h"
#include <QMouseEvent>

SwitchButton::SwitchButton(QWidget *parent)
    : QWidget(parent), m_checked(false), m_sliderPos(0) {
    setFixedSize(40, 20);
    m_timer.setInterval(10);
    connect(&m_timer, &QTimer::timeout, this, &SwitchButton::updateAnimation);
}

/**
* @brief 返回滑动按键的bool值
*/
bool SwitchButton::isChecked() const {
    return m_checked;
}

/**
* @brief 设置滑动按键的bool值,开启绘制按键图标
* @param  checked 滑动控件对应的bool值
*/
void SwitchButton::setChecked(bool checked) {
    m_checked = checked;
    m_timer.start();
    update();
}

/**
* @brief 设置按键大小
* @param  width 宽度
* @param  height 高度
*/
void SwitchButton::setSize(int width, int height)
{
    setFixedSize(width, height);
}

void SwitchButton::paintEvent(QPaintEvent *) {
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    // 绘制背景
    QRectF bgRect(0, 0, width(), height());
    painter.setPen(Qt::NoPen);
    painter.setBrush(m_checked ? m_bgColorOn : m_bgColorOff);
    painter.drawRoundedRect(bgRect, m_radius, m_radius);

    // 绘制滑块
    qreal sliderSize = height() * 0.9;
    QRectF sliderRect(m_sliderPos, height()*0.05,
                     sliderSize, sliderSize);
    painter.setBrush(m_sliderColor);
    painter.drawEllipse(sliderRect);
}

void SwitchButton::mousePressEvent(QMouseEvent *) {
    m_checked = !m_checked;
    m_timer.start();
    emit toggled(m_checked);
    update();
}

void SwitchButton::mouseReleaseEvent(QMouseEvent *) {
    // 可添加点击效果
}

void SwitchButton::resizeEvent(QResizeEvent *) {
    m_radius = height() / 2.0;
    m_sliderPos = m_checked ? width() - height()*0.95 : height()*0.05;
}

void SwitchButton::updateAnimation() {
    qreal targetPos = m_checked ? width() - height()*0.95 : height()*0.05;
    if (qAbs(m_sliderPos - targetPos) < 0.5) {
        m_sliderPos = targetPos;
        m_timer.stop();
    } else {
        m_sliderPos += (targetPos - m_sliderPos) * 0.2;
    }
    update();
}
